<template>
  <view class="page-container">
    <!-- 背景装饰 -->
    <view class="background-decoration">
      <view class="decoration-circle circle-1"></view>
      <view class="decoration-circle circle-2"></view>
      <view class="decoration-circle circle-3"></view>
    </view>

    <!-- 页面头部 -->
    <view class="page-header">
      <view class="header-content">
        <text class="page-title">待办任务</text>
        <text class="page-subtitle" v-if="total > 0">共 {{ total }} 项待处理</text>
        <text class="page-subtitle" v-else>暂无待办事项</text>
      </view>
    </view>

    <!-- 数据列表 -->
    <view class="content-section">
      <view class="card-list" v-if="paginatedTaskList.length > 0">
        <view
          v-for="(item, index) in paginatedTaskList"
          :key="item.id"
          class="task-card"
          @tap="handleOpen(item)"
          :class="{ 'card-active': activeCard === index }"
          @touchstart="setActiveCard(index)"
          @touchend="clearActiveCard"
        >
          <!-- 卡片装饰线 -->
          <view class="card-decoration" :style="{ background: getCardColor(index) }"></view>

          <!-- 卡片内容 -->
          <view class="card-content">
            <view class="card-header">
              <view class="flow-info">
                <view class="flow-name">
                  <view class="priority-indicator" :class="getPriorityClass(index)"></view>
                  <text class="item-number">{{ (queryParams.pageNum - 1) * queryParams.pageSize + index + 1 }}</text>
                  <text class="flow-title">{{ item.flowName || '未知流程' }}</text>
                </view>
                <view class="flow-meta">
                  <text class="flow-type">{{ getFlowType(item.flowName) }}</text>
                </view>
              </view>
              <view class="status-wrapper">
                <view class="flow-status" :style="{ background: getStatusColor() }">
                  <wd-icon name="clock" size="20rpx" color="#fa8c16" />
                  <text class="status-text">待办理</text>
                </view>
              </view>
            </view>

            <view class="card-body">
              <view class="task-description">
                <text class="desc-text">{{ getTaskDescription(item.flowName) }}</text>
              </view>
            </view>

            <view class="card-footer">
              <view class="applicant-info">
                <view class="avatar-wrapper" :style="{ background: getAvatarColor(index) }">
                  <text class="avatar-text">{{ getAvatarText((item as any).createByName) }}</text>
                </view>
                <view class="user-details">
                  <text class="applicant-name">{{ (item as any).createByName || '未知申请人' }}</text>
                  <text class="applicant-role">申请人</text>
                </view>
              </view>
              <view class="time-info">
                <view class="time-wrapper">
                  <wd-icon name="time" size="24rpx" color="#999999" />
                  <text class="create-time">{{ formatTime((item as any).createTime) }}</text>
                </view>
              </view>
            </view>
          </view>

          <!-- 点击波纹效果 -->
          <view class="card-ripple"></view>
        </view>
      </view>

      <!-- 空数据提示 -->
      <view v-else-if="!loading && taskList.length === 0" class="empty-state">
        <view class="empty-icon">
          <wd-icon name="document" size="120rpx" color="#CCCCCC" />
        </view>
        <text class="empty-title">暂无待办任务</text>
        <text class="empty-desc">您的待办事项将在这里显示</text>
        <view class="empty-action">
          <wd-button type="primary" size="small" @tap="getWaitingList">
            <wd-icon name="refresh" size="24rpx" />
            刷新列表
          </wd-button>
        </view>
      </view>

      <!-- 加载提示 -->
      <view v-if="loading" class="loading-state">
        <view class="loading-spinner">
          <view class="spinner-ring"></view>
          <view class="spinner-ring"></view>
          <view class="spinner-ring"></view>
        </view>
        <text class="loading-text">正在加载待办任务...</text>
      </view>

      <!-- 分页组件 -->
      <view class="pagination-wrapper" v-show="total > 0">
        <wd-pagination
          v-model="queryParams.pageNum"
          :page-size="queryParams.pageSize"
          :total="total"
          @change="handleChange"
          show-icon
          show-message
          :hide-if-one-page="false"
        />

      </view>
    </view>
  </view>
</template>
  
<script setup lang="ts">
import { pageByTaskWait } from '@/pagesA/api/workflow/task/index';
import type { TaskQuery, FlowTaskVO } from '@/pagesA/api/workflow/task/types';

import { ref, onMounted, reactive, computed } from 'vue';
import type { RouterJumpVo } from '@/pagesA/api/workflow/workflowCommon/types';
import workflowCommon from '@/pagesA/api/workflow/workflowCommon';
import { onLoad, onShow } from '@dcloudio/uni-app';
// 遮罩层
const loading = ref(true);
// 总条数
const total = ref(0);
// 模型定义表格数据
const taskList = ref<FlowTaskVO[]>([]);
// 活动卡片索引
const activeCard = ref(-1);


// 查询参数
const queryParams = ref<TaskQuery>({
  pageNum: 1,
  pageSize: 10,
  nodeName: undefined,
  flowName: undefined,
  flowCode: undefined,
  createByIds: []
});

// 分页后的任务列表
const paginatedTaskList = computed(() => {
  const start = (queryParams.value.pageNum - 1) * queryParams.value.pageSize;
  const end = start + queryParams.value.pageSize;
  return taskList.value.slice(start, end);
});
onShow(() => {
  getWaitingList();
});

// 分页变化处理函数（前端分页，不重新请求数据）
const handleChange = (val: number) => {
  console.log("📄 分页变化:", val);
  queryParams.value.pageNum = val;

  console.log("📋 分页后数据:", {
    currentPage: val,
    pageSize: queryParams.value.pageSize,
    totalItems: taskList.value.length,
    currentPageItems: paginatedTaskList.value.length
  });
};

//获取所有数据，前端分页
const getWaitingList = () => {
  loading.value = true;

  // 创建一个获取所有数据的查询参数
  const allDataParams = {
    ...queryParams.value,
    pageNum: 1,
    pageSize: 1000 // 设置一个较大的值来获取所有数据
  };

  pageByTaskWait(allDataParams).then((resp: any) => {
    console.log("📊 API响应数据:", resp);

    // 处理不同的响应格式
    if (resp && resp.data) {
      // 如果响应有data字段
      taskList.value = resp.data.rows || resp.data.records || resp.data || [];
      total.value = resp.data.total || resp.data.size || taskList.value.length;
    } else if (resp && resp.rows) {
      // 如果响应直接有rows字段
      taskList.value = resp.rows || [];
      total.value = resp.total || taskList.value.length;
    } else if (Array.isArray(resp)) {
      // 如果响应直接是数组
      taskList.value = resp;
      total.value = resp.length;
    } else {
      // 默认处理
      taskList.value = [];
      total.value = 0;
    }

    console.log("📋 处理后的数据:", {
      allTaskList: taskList.value,
      total: total.value,
      currentPage: queryParams.value.pageNum,
      pageSize: queryParams.value.pageSize,
      paginatedCount: paginatedTaskList.value.length
    });

    loading.value = false;
  }).catch((error) => {
    console.error("❌ API请求失败:", error);
    taskList.value = [];
    total.value = 0;
    loading.value = false;
  });
};
// 格式化时间 - iOS兼容版本（增强版）
const formatTime = (timeStr: any) => {
  if (!timeStr) return '-';

  try {
    // 转换为字符串
    const timeString = String(timeStr);

    // 多种格式兼容处理
    let formattedTimeStr = timeString;

    // 处理 "2025-07-04 13:21:07" 格式 -> "2025/07/04 13:21:07"
    if (timeString.match(/^\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}$/)) {
      formattedTimeStr = timeString.replace(/-/g, '/');
    }
    // 处理 "2025-07-04" 格式 -> "2025/07/04"
    else if (timeString.match(/^\d{4}-\d{2}-\d{2}$/)) {
      formattedTimeStr = timeString.replace(/-/g, '/');
    }
    // 处理 "2025-07-04T13:21:07" ISO格式 -> "2025/07/04 13:21:07"
    else if (timeString.includes('T')) {
      formattedTimeStr = timeString.replace(/-/g, '/').replace('T', ' ').split('.')[0];
    }

    const date = new Date(formattedTimeStr);

    // 检查日期是否有效
    if (isNaN(date.getTime())) {
      return timeString; // 如果无法解析，返回原始字符串
    }

    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
  } catch (error) {
    console.error('时间格式化错误:', error, '原始值:', timeStr);
    return String(timeStr);
  }
};

//办理
const handleOpen = async (row: FlowTaskVO) => {
const routerJumpVo = reactive<RouterJumpVo>({
  businessId: row.businessId,
  taskId: row.id,
  type: 'approval',
  formCustom: row.formCustom,
  formPath: row.formPath
});
workflowCommon.routerJump(routerJumpVo);
};

// 卡片交互函数
const setActiveCard = (index: number) => {
  activeCard.value = index;
};

const clearActiveCard = () => {
  activeCard.value = -1;
};

// 获取卡片装饰色
const getCardColor = (index: number) => {
  const colors = [
    'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
    'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)',
    'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)',
    'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)',
    'linear-gradient(135deg, #fa709a 0%, #fee140 100%)',
    'linear-gradient(135deg, #a8edea 0%, #fed6e3 100%)'
  ];
  return colors[index % colors.length];
};

// 获取优先级样式
const getPriorityClass = (index: number) => {
  const classes = ['priority-high', 'priority-medium', 'priority-low'];
  return classes[index % classes.length];
};

// 获取流程类型
const getFlowType = (flowName: string) => {
  if (!flowName) return '通用';
  if (flowName.includes('申请')) return '申请类';
  if (flowName.includes('审批')) return '审批类';
  if (flowName.includes('报销')) return '财务类';
  if (flowName.includes('合同')) return '合同类';
  return '其他';
};

// 获取状态颜色
const getStatusColor = () => {
  return 'linear-gradient(135deg, #fff7e6 0%, #ffe7ba 100%)';
};

// 获取任务描述
const getTaskDescription = (flowName: string) => {
  const descriptions: { [key: string]: string } = {
    '请假申请': '员工请假申请需要审批',
    '报销申请': '费用报销单据待处理',
    '合同审批': '合同条款需要审核确认',
    '采购申请': '物资采购申请待审批',
    '项目立项': '新项目立项申请审核'
  };
  return descriptions[flowName] || '工作流程待处理，请及时审批';
};

// 获取头像文字
const getAvatarText = (name: string) => {
  if (!name) return '?';
  return name.charAt(name.length - 1);
};

// 获取头像颜色
const getAvatarColor = (index: number) => {
  const colors = [
    'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
    'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)',
    'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)',
    'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)',
    'linear-gradient(135deg, #fa709a 0%, #fee140 100%)',
    'linear-gradient(135deg, #a8edea 0%, #fed6e3 100%)'
  ];
  return colors[index % colors.length];
};


</script>
  
<style lang="scss" scoped>
.page-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
  overflow-x: hidden;
}

/* 背景装饰 */
.background-decoration {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  overflow: hidden;
  z-index: 0;
}

.decoration-circle {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  animation: float 6s ease-in-out infinite;
}

.circle-1 {
  width: 200rpx;
  height: 200rpx;
  top: 10%;
  right: -50rpx;
  animation-delay: 0s;
}

.circle-2 {
  width: 150rpx;
  height: 150rpx;
  top: 60%;
  left: -30rpx;
  animation-delay: 2s;
}

.circle-3 {
  width: 100rpx;
  height: 100rpx;
  top: 30%;
  left: 50%;
  animation-delay: 4s;
}

@keyframes float {
  0%, 100% { transform: translateY(0px) rotate(0deg); }
  50% { transform: translateY(-20rpx) rotate(180deg); }
}

/* 页面头部 */
.page-header {
  padding: 80rpx 40rpx 40rpx;
  text-align: center;
  position: relative;
  z-index: 2;
}

.header-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10rpx;
}

.page-title {
  font-size: 48rpx;
  font-weight: 700;
  color: #ffffff;
  text-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.2);
  letter-spacing: 2rpx;
}

.page-subtitle {
  font-size: 26rpx;
  color: rgba(255, 255, 255, 0.8);
  font-weight: 400;
}

/* 内容区域 */
.content-section {
  padding: 0 30rpx 40rpx;
  position: relative;
  z-index: 2;
}

.card-list {
  display: flex;
  flex-direction: column;
  gap: 24rpx;
}

/* 任务卡片 */
.task-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20rpx);
  border-radius: 24rpx;
  padding: 0;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
  border: 1rpx solid rgba(255, 255, 255, 0.2);
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
  cursor: pointer;

  &:hover {
    transform: translateY(-8rpx) scale(1.02);
    box-shadow: 0 16rpx 48rpx rgba(0, 0, 0, 0.15);
  }

  &.card-active {
    transform: translateY(-4rpx) scale(0.98);
    box-shadow: 0 12rpx 40rpx rgba(0, 0, 0, 0.12);
  }
}

/* 卡片装饰线 */
.card-decoration {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 6rpx;
  border-radius: 24rpx 24rpx 0 0;
}

/* 卡片内容 */
.card-content {
  padding: 30rpx;
}

/* 卡片头部 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20rpx;
}

.flow-info {
  flex: 1;
  margin-right: 20rpx;
}

.flow-name {
  display: flex;
  align-items: center;
  margin-bottom: 8rpx;
}

.priority-indicator {
  width: 8rpx;
  height: 8rpx;
  border-radius: 50%;
  margin-right: 12rpx;

  &.priority-high {
    background: #ff4d4f;
    box-shadow: 0 0 8rpx rgba(255, 77, 79, 0.4);
  }

  &.priority-medium {
    background: #faad14;
    box-shadow: 0 0 8rpx rgba(250, 173, 20, 0.4);
  }

  &.priority-low {
    background: #52c41a;
    box-shadow: 0 0 8rpx rgba(82, 196, 26, 0.4);
  }
}

.item-number {
  font-size: 24rpx;
  color: #999999;
  font-weight: 500;
  margin-right: 8rpx;
}

.flow-title {
  font-size: 32rpx;
  font-weight: 700;
  color: #333333;
  line-height: 1.4;
}

.flow-meta {
  margin-top: 4rpx;
}

.flow-type {
  font-size: 22rpx;
  color: #667eea;
  background: rgba(102, 126, 234, 0.1);
  padding: 4rpx 12rpx;
  border-radius: 12rpx;
  border: 1rpx solid rgba(102, 126, 234, 0.2);
  font-weight: 500;
}

/* 状态区域 */
.status-wrapper {
  flex-shrink: 0;
}

.flow-status {
  display: flex;
  align-items: center;
  gap: 8rpx;
  padding: 12rpx 20rpx;
  border-radius: 20rpx;
  border: 1rpx solid rgba(250, 140, 22, 0.2);
}

.status-text {
  font-size: 24rpx;
  color: #fa8c16;
  font-weight: 600;
}

/* 卡片主体 */
.card-body {
  margin-bottom: 24rpx;
}

.task-description {
  background: rgba(102, 126, 234, 0.05);
  border-left: 4rpx solid #667eea;
  padding: 16rpx 20rpx;
  border-radius: 0 12rpx 12rpx 0;
}

.desc-text {
  font-size: 26rpx;
  color: #666666;
  line-height: 1.5;
}

/* 卡片底部 */
.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.applicant-info {
  display: flex;
  align-items: center;
  gap: 16rpx;
}

.avatar-wrapper {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.avatar-text {
  font-size: 24rpx;
  color: #ffffff;
  font-weight: 700;
}

.user-details {
  display: flex;
  flex-direction: column;
  gap: 4rpx;
}

.applicant-name {
  font-size: 28rpx;
  color: #333333;
  font-weight: 600;
}

.applicant-role {
  font-size: 22rpx;
  color: #999999;
}

/* 时间信息 */
.time-info {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 8rpx;
}

.time-wrapper {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.create-time {
  font-size: 24rpx;
  color: #666666;
}

.urgency-tag {
  padding: 6rpx 12rpx;
  border-radius: 12rpx;
  font-size: 20rpx;
  font-weight: 600;

  &.urgency-high {
    background: rgba(255, 77, 79, 0.1);
    color: #ff4d4f;
    border: 1rpx solid rgba(255, 77, 79, 0.2);
  }

  &.urgency-medium {
    background: rgba(250, 173, 20, 0.1);
    color: #faad14;
    border: 1rpx solid rgba(250, 173, 20, 0.2);
  }

  &.urgency-low {
    background: rgba(82, 196, 26, 0.1);
    color: #52c41a;
    border: 1rpx solid rgba(82, 196, 26, 0.2);
  }
}

.urgency-text {
  font-size: 20rpx;
}

/* 点击波纹效果 */
.card-ripple {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: radial-gradient(circle, rgba(102, 126, 234, 0.1) 0%, transparent 70%);
  opacity: 0;
  transition: opacity 0.3s ease;
  pointer-events: none;
}

.task-card:active .card-ripple {
  opacity: 1;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 40rpx;
  text-align: center;
}

.empty-icon {
  margin-bottom: 30rpx;
  opacity: 0.6;
}

.empty-title {
  font-size: 32rpx;
  color: rgba(255, 255, 255, 0.9);
  font-weight: 600;
  margin-bottom: 10rpx;
}

.empty-desc {
  font-size: 26rpx;
  color: rgba(255, 255, 255, 0.7);
  margin-bottom: 40rpx;
}

.empty-action {
  margin-top: 20rpx;
}

/* 加载状态 */
.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 40rpx;
  text-align: center;
}

.loading-spinner {
  position: relative;
  width: 80rpx;
  height: 80rpx;
  margin-bottom: 30rpx;
}

.spinner-ring {
  position: absolute;
  width: 100%;
  height: 100%;
  border: 4rpx solid transparent;
  border-top: 4rpx solid rgba(255, 255, 255, 0.8);
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

.spinner-ring:nth-child(2) {
  width: 60rpx;
  height: 60rpx;
  top: 10rpx;
  left: 10rpx;
  animation-delay: -0.3s;
  border-top-color: rgba(255, 255, 255, 0.6);
}

.spinner-ring:nth-child(3) {
  width: 40rpx;
  height: 40rpx;
  top: 20rpx;
  left: 20rpx;
  animation-delay: -0.6s;
  border-top-color: rgba(255, 255, 255, 0.4);
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  font-size: 28rpx;
  color: rgba(255, 255, 255, 0.8);
  font-weight: 500;
}

/* 分页组件 */
.pagination-wrapper {
  margin-top: 40rpx;
  padding: 30rpx;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20rpx);
  border-radius: 20rpx;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
  border: 1rpx solid rgba(255, 255, 255, 0.2);

  :deep(.wd-pagination) {
    justify-content: center;

    .wd-pagination__item {
      margin: 0 8rpx;
      border-radius: 12rpx;
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      font-weight: 500;
      min-width: 60rpx;
      height: 60rpx;
      display: flex;
      align-items: center;
      justify-content: center;

      &:hover {
        transform: translateY(-2rpx) scale(1.05);
        box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.2);
      }

      &.wd-pagination__item--active {
        background: linear-gradient(135deg, #667eea, #764ba2);
        color: #ffffff;
        box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.3);
      }
    }

    .wd-pagination__prev,
    .wd-pagination__next {
      background: rgba(102, 126, 234, 0.1);
      border: 1rpx solid rgba(102, 126, 234, 0.2);
      color: #667eea;

      &:hover {
        background: rgba(102, 126, 234, 0.2);
      }
    }
  }
}

.debug-info {
  margin-top: 20rpx;
  padding: 20rpx;
  background: rgba(0, 0, 0, 0.05);
  border-radius: 12rpx;
  font-size: 24rpx;
  color: #666666;

  text {
    display: block;
    margin-bottom: 8rpx;
  }
}

/* 响应式设计 */
@media screen and (max-width: 750rpx) {
  .page-header {
    padding: 60rpx 30rpx 30rpx;
  }

  .page-title {
    font-size: 42rpx;
  }

  .content-section {
    padding: 0 20rpx 30rpx;
  }

  .card-content {
    padding: 24rpx;
  }

  .flow-title {
    font-size: 28rpx;
  }

  .card-footer {
    flex-direction: column;
    align-items: flex-start;
    gap: 16rpx;
  }

  .time-info {
    align-items: flex-start;
  }
}

/* 动画增强 */
.task-card {
  animation: slideInUp 0.6s ease-out;
}

.task-card:nth-child(1) { animation-delay: 0.1s; }
.task-card:nth-child(2) { animation-delay: 0.2s; }
.task-card:nth-child(3) { animation-delay: 0.3s; }
.task-card:nth-child(4) { animation-delay: 0.4s; }

@keyframes slideInUp {
  from {
    opacity: 0;
    transform: translateY(30rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>